<?php

// +----------------------------------------------------------------------
// | Easyadmin
// +----------------------------------------------------------------------
// | PHP交流群: 763822524
// +----------------------------------------------------------------------
// | 开源协议  https://mit-license.org 
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zhongshaofa/EasyAdmin
// +----------------------------------------------------------------------

namespace app\admin\controller\user;

//用户表
use app\admin\model\website\Prohibit;
use app\admin\model\website\Users as UsersModel;

//用户组表
use app\admin\model\website\UserGroup as UserGroupModel;

//房间号
use app\admin\model\website\Rooms as RoomsModel;

//公共
use app\admin\service\TriggerService;
use app\common\controller\AdminController;
use app\common\service\TenImService;
use broadcast\redis\RedisService;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use Exception;
use think\App;
use broadcast\redis\setRedis;

/**
 * Class Admin
 * @package app\admin\controller\system
 * @ControllerAnnotation(title="站点管理")
 */
class User extends AdminController
{

    use \app\admin\traits\Curd;

    protected $sort = [
        'id' => 'desc',
    ];

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new UsersModel();
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();

            $countModel = $this->model->where($where);

            if (session("admin.group") != 1 && session("admin.group") != '5' && session("admin.group") != '6') {
                $countModel->where('extension', session("admin.username"));
            } else if (session("admin.group") != 1 && session("admin.group") != '5') {
                $countModel->where('rooms', 'in', explode(",", session("admin.rooms")));
                $countModel->where("group", "not in", "1,4,5,6");
            } else if (session('admin.group') == 5) {
                $countModel->where('rooms', 'in', explode(",", session("admin.rooms")));
                $countModel->where("group", "not in", "1,4,5");
            }

            $count = $countModel->where("username", "<>", "system")->count();

            $listModel = $this->model->where($where);
            if (session("admin.group") != 1 && session("admin.group") != '5' && session("admin.group") != '6') {
                $listModel->where('extension', session("admin.username"));
            } else if (session("admin.group") != 1 && session("admin.group") != '5') {
                $listModel->where('rooms', 'in', explode(",", session("admin.rooms")));
                $listModel->where("group", "not in", "1,4,5,6");
            } else if (session('admin.group') == 5) {
                $listModel->where('rooms', 'in', explode(",", session("admin.rooms")));
                $listModel->where("group", "not in", "1,4,5");
            }

            // 获取禁言列表
            $forbidList = TenImService::getGroupShuttedUin(['GroupId' => TenImService::getGroupId()])['ShuttedUinList'];

            $forbidUsers = [];
            foreach ($forbidList as $item) {
                $forbidUsers[] = $item['Member_Account'];
            }

            // 获取禁言IP
            $forbidIps = Prohibit::column('ip');


            $list = $listModel->page($page, $limit)
                ->order($this->sort)
                ->where("username", "<>", "system")
                ->select()->each(function ($item) use ($forbidIps, $forbidUsers) {
                    if (in_array($item['create_ip'], $forbidIps)) {
                        $item['is_forbidip'] = 1;
                    } else {
                        $item['is_forbidip'] = 0;
                    }
                    $item['create_ip'] = getIp($item['create_ip']);
                    if ($item['create_ip'] == '0.0.0.0') $item['create_ip'] = ' -- ';
                    $item['lately_time'] = $item['lately_time'] != 0 ? date("Y-m-d H:i", $item['lately_time']) : '--';
                    if (in_array(TenImService::getAccount(1, $item)['Identifier'], $forbidUsers)) {
                        $item['is_forbid'] = 1;
                    } else {
                        $item['is_forbid'] = 0;
                    }
                });

            $data = [
                'code' => 0,
                'msg' => '',
                'count' => $count,
                'data' => $list,
            ];
            return json($data);
        }

        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        $this->getAuth();
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            if (isset($post['rooms'])) {
                if ($post['rooms'] != '') {
                    $post['rooms'] = implode(',', $post['rooms']);
                } else {
                    $post['rooms'] = implode(',', $post['rooms']);
                }
            } else {
                $post['rooms'] = session("admin.rooms");
            }
            if ($post['group'] == 1) $post['rooms'] = '';
            if ($post['group'] == 3 || $post['group'] == 6) $post['rooms'] = $post['room_only'];
            unset($post['room_only']);
            $post['create_time'] = time();
            $post['lately_time'] = time();
            $post['password'] = md5($post['password']);
            $post['extension'] = session("admin.username");

            $findUser = $this->model->where('username', $post['username'])->find();
            if ($findUser) {
                $this->error('用户名已存在!');
            }

            // 处理房间号     end
            try {
                $save = $this->model->save($post);
                //查询  并设置缓存 start
                $users = $this->model->where("id", $this->model->id)->find()->toArray();
                setRedis::setCache(session("website"), 'usersList#' . $this->model->id . ":" . $post['username'], $users, 0);
                //查询  并设置缓存  end
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }

        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $this->getAuth();
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            // 处理房间号
            if (isset($post['rooms'])) {
                if ($post['rooms'] != '') {
                    $post['rooms'] = implode(',', $post['rooms']);
                } else {
                    $post['rooms'] = implode(',', $post['rooms']);
                }
            } else {
                $post['rooms'] = session("admin.rooms");
            }
            if ($post['group'] == 1) $post['rooms'] = '';
            if ($post['group'] == 3 || $post['group'] == 6) $post['rooms'] = $post['room_only'];
            unset($post['room_only']);

            if (isset($post['password'])) {
                if ($post['password'] != '') {
                    $post['password'] = md5($post['password']);
                } else {
                    unset($post['password']);
                }
            }

            try {
                $save = $row->save($post);
                //查询数据并设置缓存             start
                $users = $this->model->where("id", $row['id'])->find()->toArray();
                setRedis::setCache(session("website"), 'usersList#' . $id . ":" . $post['username'], $users, 0);
                //查询数据并设置缓存             end
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            if ($save) {
                $adminsGroup = getAdminsGroup();
                if (in_array($post['group'], $adminsGroup)) {
                    $this->setImAdmin($post, 1);
                } else {
                    $this->setImAdmin($post, 0);
                }
            }

            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $row->rooms = explode(",", $row->rooms);
        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="删除")
     */
    public function delete($id)
    {
        $row = $this->model->whereIn('id', $id)->select();
        $row->isEmpty() && $this->error('数据不存在');
        //删除缓存
        $idList = '';
        if (is_array($id)) {
            if (in_array(1, $id)) {
                return  $this->error("超管无法删除");
            }
            $idList = implode(",", $id);
        } else {
            $idList = $id;
            if ($id == 1) return  $this->error("超管无法删除");
        }

        try {
            setRedis::delUSerCache(session("website"), $idList);
            $save = $row->delete();
        } catch (\Exception $e) {
            $this->error('删除失败');
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }

    /**
     * @NodeAnotation(title="属性修改")
     */
    public function modify()
    {
        $post = $this->request->post();
        $row = $this->model->find($post['id']);
        empty($row) && $this->error('数据不存在');
        try {
            $row->save([
                $post['field'] => $post['value'],
            ]);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('保存成功');
    }

    /**
     * 获取用户信息
     */
    public function auth()
    {
        $rules = '';
        //获取用户组
        // if (session("admin.group") == 1) {
        //     $rules = "1,857";
        // } else if (session("admin.group") == 5) {
        //     $rules = "1,857,4";
        // } else if (session("admin.group") == 6){
        //     $rules = "1,857,6,4,5";
        // }else{
        //     $rules = "1,857,6,4,5,7";
        // }
        $groups = UserGroupModel::where('id', 'not in', $rules)->select()->toArray();
        $groupList = array();
        foreach ($groups as $value) {
            $groupList[$value['id']] = $value['name'];
        }
        return json($groupList);
    }

    // 获取用户组
    public function getAuth()
    {
        //获取用户组
        if (session("admin.username") == "system") {
            $rules = "";
        } else if (session("admin.group") == 1) {
            $rules = "1,857";
        } else if (session("admin.group") == 5) {
            $rules = "1,857,4";
        } else if (session("admin.group") == 6) {
            $rules = "1,857,6,4,5";
        } else {
            $rules = "1,857,6,4,5,7";
        }
        $groups = UserGroupModel::where('id', 'not in', $rules)->select()->toArray();
        $groupList = array();
        $i = 0;
        foreach ($groups as $value) {
            $groupList[$i]['value'] = $value['id'];
            $groupList[$i]['label'] = $value['name'];
            $i++;
        }

        $this->assign("groups", $groupList);

        //获取房间号
        $where = array();
        if (session("admin.group") == 5) {
            $where['roomid'] = ['in', session("rooms")];
        }
        $rooms = RoomsModel::field("roomid")->where($where)->select()->toArray();
        $this->assign("rooms", $rooms);
    }

    //导入
    public function useimport()
    {
        $file = request()->file('file');
        $list = importinfo($file);
        $mysqlArray = array();
        foreach ($list as $value) {
            //判断用户名是否存在
            $item = array();
            $item['username'] = $value[0];

            if (!$item['username']) {
                continue;
            }
            //判断用户密码是否存在
            if (empty($value[3])) {
                $item['password'] = md5(123456);
            } else {
                $item['password'] = md5($value[3]);
            }

            //判断用户昵称是否存在
            if (empty($value[2])) {
                $item['rooms'] = session("admin.rooms");
            } else {
                $item['rooms'] = $value[2];
            }

            //判断用户昵称是否存在
            if (empty($value[1])) {
                $item['group'] = 3;
            } else {
                switch ($value[1]) {
                    case '房间管理员':
                        $item['group'] = 6;
                        break;
                    case '总管理员':
                        $item['group'] = 5;
                        break;
                    case '讲师':
                        $item['group'] = 4;
                        break;
                    case '会员':
                        $item['group'] = 3;
                        break;
                    case '超级管理员':
                        $item['group'] = 1;
                        break;
                }
            }


            //处理基础数据
            $item['create_time'] = time();
            $item['extension'] = session("admin.username");
            $mysqlArray[] = $item;
        }

        $useAll = array_column($mysqlArray, 'username');
        // 检测表格 用户名称是否重复
        $repeat_arr = $this->checkRepetition($useAll);
        if ($repeat_arr) {
            $this->error('表格用户名称 [' . implode(', ', $repeat_arr) . '] 重复');
        }
        $repeatUser = UsersModel::where("username", 'in', $useAll)->column('username');

        $match = array();

        foreach ($repeatUser as $value) {
            $value = trim($value);
            if (array_search(strtolower($value), $useAll)) {
                $value = array_search(strtolower($value), $useAll);
            } else if (array_search(strtoupper($value), $useAll)) {
                $value = array_search(strtoupper($value), $useAll);
            } else {
                $value = array_search($value, $useAll);
            }
            if ($value)
                $match[] = $value;
        }

        foreach ($match as $value) {
            unset($mysqlArray[$value]);
        }


        try {
            $nowUser = array_column($mysqlArray, 'username');
            $nowUser = implode(",", $nowUser);
            $userModel = new UsersModel;
            $res = $userModel->saveAll($mysqlArray);

            //获取所有用户
            $nowUserList = UsersModel::where("username", "in", $nowUser)->select();
            if ($nowUserList) $nowUserList = $nowUserList->toArray();
            foreach ($nowUserList as $value) {
                setRedis::setCache(session("website"), 'usersList#' . $value['id'] . ":" . $value['username'], $value, 0);
            }
            return $res ? app("json")->success("导入成功", $repeatUser) : app("json")->fail("导入失败");
        } catch (Exception $e) {
            return app("json")->fail("导入失败");
        }
    }

    //批量创建 
    public function addall()
    {
        $this->getAuth();
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            if ($post['startsuffix'] > $post['endsuffix']) {
                return $this->error('后缀的开始数字不能大于结束数字');
            }

            if ((int)$post['endsuffix'] - (int)$post['startsuffix'] > 500) {
                $post['endsuffix'] = (int)$post['startsuffix'] + 500;
            }

            $userList = array();

            for ($i = (int)$post['startsuffix']; $i <= (int)$post['endsuffix']; $i++) {

                $item = array();
                $item['username'] = $post['prefix'] . $i;
                // $item['nickname'] = $post['prefix'].$i;
                if ($post['password'] != '') {
                    $item['password'] = md5($post['password']);
                } else {
                    $item['password'] = md5(123456);
                }
                $item['sex'] = 1;
                $item['create_time'] = time();
                $item['extension'] = session("admin.username");
                $item['group'] = 3;

                $item['rooms'] = isset($post['rooms']) ? $post['rooms'] : session("admin.rooms");
                $userList[] = $item;
            }
            $useAll = array_column($userList, 'username');
            $repeatUser = UsersModel::where("username", 'in', $useAll)->column('username');

            $match = array();

            foreach ($repeatUser as $value) {
                $value = trim($value);
                if (array_search(strtolower($value), $useAll)) {
                    $value = array_search(strtolower($value), $useAll);
                } else if (array_search(strtoupper($value), $useAll)) {
                    $value = array_search(strtoupper($value), $useAll);
                } else {
                    $value = array_search($value, $useAll);
                }
                if ($value)
                    $match[] = $value;
            }


            foreach ($match as $value) {
                unset($userList[$value]);
            }

            try {
                $userModel = new UsersModel;
                $userModel->saveAll($userList);
                $nowUser = array_column($userList, 'username');
                $nowUser = implode(",", $nowUser);
                //获取所有用户
                $nowUserList = UsersModel::where("username", "in", $nowUser)->select();
                if ($nowUserList) $nowUserList = $nowUserList->toArray();
                foreach ($nowUserList as $value) {
                    setRedis::setCache(session("website"), 'usersList#' . $value['id'] . ":" . $value['username'], $value, 0);
                }
            } catch (Exception $e) {
            }
            $this->success("添加成功");
        }
        return $this->fetch();
    }

    public function forbidSendMsg($id, $ShutUpTime = 86400 * 365)
    {
        $row = $this->model->whereIn('id', $id)->select();
        $row->isEmpty() && $this->error('数据不存在');

        $row = $row->toArray();
        foreach ($row as $item) {
            // 获取禁言IM账户
            $account = TenImService::getAccount(1, $item);
            if ($account) {
                $Members_Account[] = $account['Identifier'];
            }
        }


        $params = [
            'GroupId' => TenImService::getGroupId(),
            'Members_Account' => $Members_Account,
            'ShutUpTime' => $ShutUpTime
        ];

        $res = TenImService::forbidSendMsg($params);
        if ($res['ActionStatus'] == 'OK') {
            $this->success('执行成功');
        }

        $this->error('执行失败');
    }


    /**
     * 禁IP
     * @param $id
     * @param int $type 0 正常 1 禁言
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function forbidIp($id, $type = 1)
    {
        $row = $this->model->whereIn('id', $id)->field('create_ip as ip')->select();
        $row->isEmpty() && $this->error('数据不存在');

        $row = $row->toArray();
        try {
            if ($type) {
                foreach ($row as &$item) {
                    $item['create_time'] = time();
                    $item['operation'] = session('admin.username');
                }
                $res = Prohibit::insertAll($row);
            } else {
                $ips = [];
                foreach ($row as $item) {
                    $ips[] = $item['ip'];
                }
                $res = Prohibit::whereIn('ip', $ips)->delete();
            }
        } catch (\Exception $e) {
            $this->error('执行失败');
        }
        $res ? $this->success('执行成功') : $this->error('执行失败');
    }


    /**
     * 设置IM会员成为管理员获取
     * @param $user 账户
     * @param int $status 0:会员 1:房间管理
     * @return mixed
     * @throws \think\Exception
     */
    public function setImAdmin($user, $type = 1)
    {

        $account = TenImService::getAccount(1, $user);
        // 获取用户IM昵称
        $redis = new RedisService(config('cache')['stores']['single']);
        $userSigkey = 'imUser:' . $account['Identifier'];
        $userImNick = $redis->hGet($userSigkey, 'Nick');
        $userGroup = spliceStr($userImNick, '_X_', '');
        if ($userImNick && $userGroup != $user['group']) {
            // 修改用户群权限
            $params['GroupId'] = TenImService::getGroupId();
            $params['Member_Account'] = $account['Identifier'];
            if ($type) {
                $params['Role'] = 'Admin';
            } else {
                $params['Role'] = 'Member';
            }
            TenImService::modifyGroupMemberInfo($params);

            // 修改用户IM昵称
            $userImNewNick = str_replace("_X_{$userGroup}", "_X_{$user['group']}", $userImNick);
            $data = [
                'From_Account' => $account['Identifier'],
                'ProfileItem' => [
                    ['Tag' => 'Tag_Profile_IM_Nick', 'Value' => $userImNewNick]
                ]
            ];
            TenImService::setUserProfile($data);
            $redis->hSet($userSigkey, 'Nick', $userImNewNick);
        }
    }

    private function checkRepetition($arr)
    {
        $unique_arr = array_unique($arr);
        $repeat_arr = array_diff_assoc($arr, $unique_arr);
        return $repeat_arr;
    }
}
